<template>
    <div style="width: 100%;height: 100%;position: relative;">
        <div id="map" style="width: 100%;height: 100%;"></div>
        <!--绘制条件-->
        <FloatPopup
                style="
                    width: 350px;
                    position: absolute;
                    border: 3px solid rgba(255, 214, 0, 1);
                    background-color: rgba(255, 13, 0, 0.4);
                    padding: 5px 0;
                  "
                :visible="true"
                :showClose="false"
                :left="30"
                :top="30"
        >
            <el-form
                    class="transparent-form"
                    :model="form"
                    label-width="80px">
                <el-form-item label="围栏名称">
                    <el-input v-model="form.fenceName" style="width: 230px;"></el-input>
                </el-form-item>
                <el-form-item label="绘制类型">
                    <el-select v-model="form.drawType" style="width: 230px;">
                        <el-option label="多边形" value="polygon"></el-option>
                        <el-option label="矩形" value="rectangle"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="围栏类型">
                    <el-select v-model="form.fenceType" style="width: 230px;">
                        <el-option label="进去告警" value="in"></el-option>
                        <el-option label="出去告警" value="out"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="围栏颜色">
                    <el-select v-model="form.fenceColor" style="width: 230px;">
                        <el-option label="红" value="red"></el-option>
                        <el-option label="蓝" value="blue"></el-option>
                        <el-option label="绿" value="green"></el-option>
                        <el-option label="黑" value="blank"></el-option>
                        <el-option label="白" value="white"></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div style="
            display: flex;
            justify-content: center;
            align-items: center;">
                <el-button size="small" @click="startDraw" :loading="fenceStatus==1">
                    <span v-if="fenceStatus!=1 && drawList.length==0">开始绘制</span>
                    <span v-if="fenceStatus!=1 && drawList.length>0">继续绘制</span>
                    <span v-if="fenceStatus==1">绘制中</span>
                </el-button>
                <el-button size="small" @click="clearDraw" :disabled="!(fenceStatus==2 && drawList.length>0)">
                    清空绘制
                </el-button>
                <el-button size="small" @click="saveDraw" type="primary" :disabled="!(fenceStatus==2 && drawList.length>0)">
                    保存
                </el-button>
            </div>
            <div style="display: flex;align-items: center;justify-content: center;margin-top: 6px;">
                <div style="color: gold;font-weight: bold;font-size: 13px;letter-spacing: 2px;">#双击|右键完成绘制#</div>
            </div>
        </FloatPopup>
        <!--回显条件-->
        <FloatPopup
                style="
                    width: 350px;
                    position: absolute;
                    border: 3px solid rgba(255, 214, 0, 1);
                    background-color: rgba(255, 13, 0, 0.4);
                    padding: 10px;
                  "
                :visible="true"
                :showClose="false"
                :right="30"
                :top="30"
        >
            <div>
                <el-input
                        type="textarea"
                        :rows="2"
                        placeholder="请输入内容"
                        v-model="textarea">
                </el-input>
            </div>
            <div style="display: flex;justify-content: center;padding-top: 5px;">
                <el-button size="small" @click="echoDraw" type="primary">
                    绘制
                </el-button>
            </div>
        </FloatPopup>
        <!--火车线-->
        <FloatPopup
                style="
                    width: 350px;
                    position: absolute;
                    border: 3px solid rgba(255, 214, 0, 1);
                    background-color: rgba(255, 13, 0, 0.4);
                    padding: 10px;
                  "
                :visible="true"
                :showClose="false"
                :right="30"
                :bottom="30"
        >
            <div style="display: flex;flex-direction: column; align-items: center;gap: 5px;">
                <el-button size="mini" round @click="initEnv" style=" width: 120px !important;margin-left: 0 !important; ">
                    调接口拿数据
                </el-button>
                <el-button size="mini" round @click="startMove" style=" width: 120px !important;margin-left: 0 !important; ">
                    开始
                </el-button>
                <el-button size="mini" round @click="pauseMove" style=" width: 120px !important;margin-left: 0 !important; ">
                    暂停
                </el-button>
                <el-button size="mini" round @click="continueMove" style=" width: 120px !important;margin-left: 0 !important; ">
                    继续
                </el-button>
                <el-button size="mini" round @click="speedUp" style=" width: 120px !important;margin-left: 0 !important; ">
                    加速
                </el-button>
                <el-button size="mini" round @click="speedDown" style=" width: 120px !important;margin-left: 0 !important; ">
                    减速
                </el-button>
            </div>
        </FloatPopup>
        <!--描点判断在圈内圈外-->
        <FloatPopup
                style="
                    width: 350px;
                    position: absolute;
                    border: 3px solid rgba(255, 214, 0, 1);
                    background-color: rgba(255, 13, 0, 0.4);
                    padding: 10px;
                  "
                :visible="true"
                :showClose="false"
                :left="30"
                :bottom="30"
        >
            <div style="display: flex;justify-content: center;gap: 10px;">
                <el-input
                        size="mini"
                        placeholder="纬度"
                        v-model="lat"
                        clearable>
                </el-input>
                <el-input
                        size="mini"
                        placeholder="经度"
                        v-model="lng"
                        clearable>
                </el-input>
            </div>
            <div style="display: flex;justify-content: center;padding-top:  5px;">
                <el-button size="mini" round @click="checkBtn" style=" width: 120px !important;margin-left: 0 !important; ">
                    描点判断
                </el-button>
            </div>
        </FloatPopup>

    </div>
</template>
<script>
    import maps from '@/util/bigMap'
    import FloatPopup from "@/views/test004/Dialog001/FloatPopup.vue";
    import mJson from "@/assets/json/轨迹回放数据.json";


    let BM;
    let map;
    //绘制参数
    let edit;//初始化鼠标绘制的编辑对象
    let draw;//初始化鼠标绘制的编辑对象
    //火车线参数
    let polyline; //轨迹线
    let passedLine;//已走过路径
    let currentMarker; //当前点
    export default {
        components: {FloatPopup},
        mounted() {
            this.initMap();
        },
        beforeDestroy() {
            if (map) {
                map.remove();
            }
        },
        data() {
            return {
                form: {
                    fenceName: "",
                    drawType: "polygon",
                    fenceType: "in",
                    fenceColor: "red",
                },
                fenceStatus: 0,//绘制状态【0:未开始;1:绘制中;2:已完成】
                drawList: [],//已绘制的图形
                //回显参数
                textarea: "{\"fenceName\":\"\",\"layers\":[{\"drawType\":\"polygon\",\"fenceType\":\"in\",\"path\":[{\"lng\":118.39828491210938,\"lat\":36.879320445642946},{\"lng\":118.3282470703125,\"lat\":36.729586958833444},{\"lng\":118.56033325195312,\"lat\":36.64716485600253},{\"lng\":118.66470336914062,\"lat\":36.91228928677531}],\"layerOptions\":{\"fillColor\":\"red\"}}]}",
                //火车线
                trainListPointsLocation: [],//存放轨迹经纬度
                trainHistoryInfo: [],//用来存放详细信息
                currentIndex: null, // 当前点的索引
                timer: null,//定时切换图标
                timerFlag: true,
                //描点判断
                lat: '36.78194',
                lng: '118.06933',
            }
        },
        methods: {
            //=======描点判断start=======
            checkBtn() {
                BM.marker([this.lat, this.lng]).addTo(map);
                let params = JSON.parse(this.textarea);
                console.log("在圈内？？", this.judgeIn(this.lat, this.lng, params.layers[0].path) ? "true" : "false");
                alert("在圈内？？" + (this.judgeIn(this.lat, this.lng, params.layers[0].path) ? "true" : "false"));
            },
            //=======描点判断end=======
            //=====火车线====start
            //初始化场景
            initEnv() {
                mJson.forEach((item) => {
                    if (item.latitude && item.longitude) {
                        this.trainHistoryInfo.push(item);
                        this.trainListPointsLocation.push([item.latitude, item.longitude]);
                    }
                });
                //添加轨迹线
                polyline = BM.polyline(this.trainListPointsLocation).addTo(map);
                map.fitBounds(polyline.getBounds());//适配一下边界，调整地图等级
                //添加初始点
                currentMarker = BM.marker(this.trainListPointsLocation[0], {
                    icon: BM.icon({
                        iconUrl: require('@/assets/images/online_train.png'),
                        iconAnchor: [25, 25],
                        iconSize: [35, 35]
                    }),
                }).addTo(map);
                //添加一条线段也记录已经路过的点
                passedLine = BM.polyline([[]], {color: "red"}).addTo(map);
                //监听当前点
                let that = this;
                currentMarker.on('update_position', function (e) {
                    that.checkMarkerFromDraw(e.target._latlng.lat, e.target._latlng.lng);
                    //每次坐标更新。然后也更新路径
                    passedLine.setLatLngs(e.path);
                    // 切换场景弹窗
                    if (e.index !== that.currentIndex) {
                        that.currentIndex = Number(e.index);
                        that.updateMarkerPopup(that.currentIndex);
                    }
                });
            },
            checkMarkerFromDraw(lat, lng) {
                let that = this;
                if (that.textarea && that.textarea != '') {
                    //判断是否在面内
                    let params = JSON.parse(that.textarea);
                    let layers = params.layers;
                    if (layers.length != null) {
                        for (let i = 0; i < layers.length; i++) {
                            let layer = layers[i];
                            let isIn = that.judgeIn(lat, lng, layer.path);
                            if (isIn) {
                                if (!that.timer) {
                                    that.startTimer();
                                }
                            } else {
                                this.clearTimer();
                            }
                        }
                    }
                }
            },
            //清除定时任务
            clearTimer(){
                clearInterval(this.timer);
                this.timer=null;
            },
            //进去区域  切换图标
            startTimer() {
                if (this.timer) {
                    this.clearTimer();
                }
                this.timer = setInterval(() => {
                    if (this.timerFlag) {
                        currentMarker.setIcon(BM.icon({
                            iconUrl: require('@/assets/images/train_red.png'),
                            iconAnchor: [25, 25], // 保持与原图标相同的锚点位置
                            iconSize: [35, 35] // 保持与原图标相同的尺寸
                        }));
                    } else {
                        currentMarker.setIcon(BM.icon({
                            iconUrl: require('@/assets/images/online_train.png'),
                            iconAnchor: [25, 25], // 保持与原图标相同的锚点位置
                            iconSize: [35, 35] // 保持与原图标相同的尺寸
                        }));
                    }
                    this.timerFlag = !this.timerFlag;
                }, 300);
            },
            //判断当前点是否在图形内:在里面-true,在外面-false
            judgeIn(lat, lng, latlngs) {
                let p = map.project([lat, lng]);
                let ps = latlngs.map(v => {
                    return [map.project(v).x, map.project(v).y];
                });
                return this.isIn([p.x, p.y], ps);
            },
            isIn(a, b, c) {
                let d = a[0];
                a = a[1];
                let e = !1, f, h, k, l, m = b.length, n = 0;
                for (l = m - 1; n < m; l = n,
                    n += 1) {
                    var p = !1;
                    f = b[n][0];
                    h = b[n][1];
                    k = b[l][0];
                    l = b[l][1];
                    if (f === d && h === a || k === d && l === a)
                        return c ? !0 : !1;
                    if (h < a === l >= a) {
                        f = (k - f) * (a - h) / (l - h) + f;
                        if (d === f)
                            return c ? !0 : !1;
                        p = d < f
                    }
                    p && (e = !e)
                }
                return e
            },
            // 更新车辆标记弹窗
            updateMarkerPopup(index) {
                if (!currentMarker.getPopup()) {
                    currentMarker.bindPopup(this.getPopupContent(index), {
                        className: "popTable",
                        closeButton: false,
                        offset: [-5, -5],
                    });
                    currentMarker.openPopup();
                } else {
                    currentMarker.setPopupContent(this.getPopupContent(index));
                    currentMarker.openPopup();
                }
            },
            // 获取弹窗内容
            getPopupContent(index) {
                const item = this.trainHistoryInfo[index] || this.trainHistoryInfo[0];
                return `
                    <div style="padding: 10px; min-width: 200px;">
                      <h3 style="margin: 0 0 10px; font-size: 16px;">机车信息</h3>
                      <p><strong>时间:</strong> ${item.createTime || '-'}</p>
                      <p><strong>线路名称:</strong> ${item.lineName || '-'}</p>
                      <p><strong>机车号:</strong> ${item.en || '-'}</p>
                      <p><strong>车次号:</strong> ${item.tn || '-'}</p>
                      <p><strong>速度:</strong> ${item.speed ? item.speed + 'km/h' : '-'}</p>
                      <p><strong>公里标:</strong> ${item.kilometer || '-'}</p>
                    </div>
              `;
            },
            //开始移动
            startMove() {
                if (!currentMarker || !polyline) return;
                currentMarker.moveAlong(polyline, 500, {
                    replay: false //默认是循环回放 replay:true
                });
            },
            //暂停移动
            pauseMove() {
                currentMarker.pauseMove();
            },
            //继续移动
            continueMove() {
                try {
                    currentMarker.resumeMove();
                } catch (error) {
                    alert('先点击开始才能点击继续哦')
                }
            },
            //加速
            speedUp() {
                currentMarker.setSpeed(currentMarker.getSpeed() + 300);
            },
            //减速
            speedDown() {
                currentMarker.setSpeed(currentMarker.getSpeed() - 100);
            },
            //=====火车线====end
            //===回显===start
            echoDraw() {
                if (!this.textarea || this.textarea == '') {
                    return;
                }
                let params = JSON.parse(this.textarea);
                for (let i = 0; i < params.layers.length; i++) {
                    let item = params.layers[i];
                    let path = item.path;
                    let bounds = [];
                    for (let j = 0; j < path.length; j++) {
                        let item2 = path[j];
                        bounds.push([item2.lat, item2.lng]);
                    }
                    if (item.drawType == 'polygon') {//绘制多边形
                        if (item.layerOptions && item.layerOptions != {}) {
                            BM.polygon(bounds, item.layerOptions).addTo(map);
                        } else {
                            BM.polygon(bounds, {color: "red", weight: 1}).addTo(map);
                        }
                    } else if (item.drawType == 'rectangle') {//绘制矩形
                        if (item.layerOptions && item.layerOptions != {}) {
                            BM.rectangle(bounds, item.layerOptions).addTo(map);
                        } else {
                            BM.rectangle(bounds, {color: "red", weight: 1}).addTo(map);
                        }
                    }
                }
            },
            //===回显===start

            //保存绘制
            saveDraw() {
                let params = {
                    fenceName: this.form.fenceName,
                    layers: []
                };
                for (let i = 0; i < this.drawList.length; i++) {
                    let item = this.drawList[i];
                    params.layers.push({
                        drawType: item.type,
                        fenceType: item.layer.fenceType,
                        path: item.path,
                        layerOptions: item.layer.options,
                    });
                }
                console.log('this.drawList', this.drawList);
                alert(JSON.stringify(params));
            },
            //开始绘制
            startDraw() {
                // 更改多边形的填充颜色
                draw.options[this.form.drawType].fillColor = this.form.fenceColor;
                this.activate(this.form.drawType);
                this.fenceStatus = 1;
            },
            //绘制生效方法
            activate(drawType) {
                edit.isEdit() && edit.disable(), draw.enable(drawType);
            },
            //重新绘制
            clearDraw() {
                this.$confirm('确认删除所有绘制图形？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    for (let i = 0; i < this.drawList.length; i++) {
                        let item = this.drawList[i];
                        map.removeLayer(item.layer); // 从地图移除
                    }
                    this.drawList = [];
                    this.fenceStatus = 0;
                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //初始化地图
            initMap() {
                let that = this;
                maps.then(() => {
                    BM = window.BM;
                    //这里之后会换成加载瓦片图的地址
                    BM.Config.HTTP_URL = "http://ua.bigemap.com:30081/bmsdk/";
                    map = BM.map('map', 'bigemap.dc-satellite', {
                        crs: BM.CRS.EPSG4326, //坐标参考系统:EPSG4326
                        center: [30.4, 104.5],
                        zoom: 7,
                        zoomControl: false,
                        attributionControl: false,
                    }).addEventListener('zoomend', function (e) {
                        this.zoomLevel = e.target._zoom;
                        console.log('当前级别 : ' + this.zoomLevel);
                    });
                    // 添加街道图层
                    BM.tileLayer("bigemap.dc-street").addTo(map);
                    // 初始化鼠标绘制的编辑对象
                    draw = new BM.Plot.Draw(map, {
                        // 是否允许是否持续绘制
                        repeat: false,
                        // 多边形的填充颜色
                        polygon: {
                            fillColor: "red",
                        },
                        //矩形的填充颜色
                        rectangle: {
                            fillColor: "red",
                        },
                    });
                    //绘制对象监听正在绘制的事件
                    draw.on("bm_draw_end", function (e) {
                        console.log('bm_draw_end', e.detail);
                        that.fenceStatus = 2;
                        let detail = e.detail;
                        detail.layer.fenceId = Date.now(); //给图层添加id
                        detail.layer.fenceType = that.form.fenceType;//添加绘制类型参数
                        that.drawList.push(detail); // 存入数组
                        //给已绘制的图添加点击事件
                        detail.layer.on("click", function () {
                            draw.disable();
                            !edit.isEdit() && edit.edit(this);
                            that.fenceStatus = 1;
                        });
                    });
                    // 初始化鼠标绘制的编辑对象
                    edit = new BM.Plot.Edit(map, {
                        control: {
                            //是否允许在编辑的时候拖动绘制图形
                            dragging: false,
                            // 顶点图标
                            vertex: {
                                autoRemove: true,
                                withIn: 10,
                                icon: BM.icon({
                                    iconUrl: "bigemap/css/images/plus.png",
                                    iconSize: [16, 16],
                                    iconAnchor: [8, 8],
                                }),
                            },
                            // 加点的图标
                            boundsMarker: {
                                icon: BM.icon({
                                    iconUrl: "bigemap/css/images/dot.png",
                                    iconSize: [16, 16],
                                    iconAnchor: [8, 8],
                                }),
                            },
                            // 点,线，圆等的编辑图标
                            marker: {
                                icon: BM.icon({
                                    iconUrl: "bigemap/css/images/dot.png",
                                    iconSize: [8, 8],
                                    iconAnchor: [4, 4],
                                }),
                            },
                        },
                    });
                    // 编辑对象监听正在编辑结束
                    edit.on("bm_edit_end", function (e) {
                        console.log('bm_edit_end', e.detail);
                        that.fenceStatus = 2;
                        let editedDetail = e.detail;
                        // 关键：通过图层唯一ID找到数组中对应的旧图层
                        const detailIndex = that.drawList.findIndex(detail => detail.layer.fenceId === editedDetail.layer.fenceId);
                        // 找到则替换，未找到则提示（正常情况应该能找到）
                        if (detailIndex !== -1) {
                            that.drawList.splice(detailIndex, 1, editedDetail); // 替换旧图层
                            console.log('图层已更新到数组中');
                        } else {
                            console.warn('未找到对应图层，可能是异常情况');
                        }
                    });
                    //  双击完成绘制
                    map.on('dblclick', function (e) {
                        draw.disable();//右键完成绘制
                        edit.disable();//右键完成编辑
                    });
                    // 右键完成绘制（同时阻止右键菜单弹出）
                    map.on('contextmenu', function (e) {
                        draw.disable();//右键完成绘制
                        edit.disable();//右键完成编辑
                    });

                });
            },
        }
    }
</script>
<style scoped>
    /* 表单容器透明 */
    ::v-deep .transparent-form {
        background-color: transparent !important;
    }

    /* 表单项透明 */
    ::v-deep .transparent-form .el-form-item {
        background-color: transparent !important;
    }

    /* 输入框透明 */
    ::v-deep .transparent-form .el-input__inner {
        background-color: transparent !important;
        border: 1px solid rgba(255, 255, 255, 0.5); /* 可选：半透明白色边框 */
        color: #fff; /* 文字颜色，根据背景调整 */
    }

    /* 标签文字颜色（如果需要） */
    ::v-deep .transparent-form .el-form-item__label {
        color: #fff; /* 根据背景调整 */
    }
</style>